package com.leecode.exercise;

public class 滑动窗口_01_长度k子数组最大和 {

    public static void main(String[] args) {
        int[] nums = {1, 4, 2, 10, 2, 3, 1, 0, 20};
        int k = 3;

        int result = maxSumSubarray(nums, k);
        System.out.println("长度为 " + k + " 的子数组和的最大值是：" + result);
    }


    // 求解长度为k的子数组和的最大值
    public static int maxSumSubarray(int[] nums, int k) {
        int maxSum = 0;
        int len = nums.length;
        //初始化K数组，认为从0开始，将k个元素加起来
        //k=3, [1, 4, 2]
        for (int i = 0; i < k; i++) {
            maxSum += nums[i];
        }

        //每移动一一个元素，计算一次，比较并替换最大值
        //1, [4, 2, 10] 2, 3, 1, 0, 20
        //1, 4, [2, 10 2], 3, 1, 0, 20
        for (int i = k; i < len; i++) {
            int currSum = maxSum-nums[i-k]+nums[i];
            maxSum = Math.max(currSum, maxSum);
        }

        return maxSum;
    }

}
